#include "databasedownloader.h"

DatabaseDownloader::DatabaseDownloader(QObject *parent) : QObject(parent) {
    accessManger = new QNetworkAccessManager(this);
    QObject::connect(accessManger, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
}

DatabaseDownloader::~DatabaseDownloader() {
    accessManger->deleteLater();
}

void DatabaseDownloader::ask(QString url, QString filePath) {
    ask(QUrl(url), filePath);
}

void DatabaseDownloader::ask(QUrl url, QString filePath) {
//    QFile f(filePath);
//    if (!f.open(QIODevice::WriteOnly)) {
//        qDebug() << "open file failed";
//        return;
//    }
    this->filePath = filePath;
    // Net request part
    QNetworkRequest request;
    request.setUrl(url);
    accessManger->get(request);
}

void DatabaseDownloader::requestFinished(QNetworkReply *reply) {
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(!statusCode.isValid()) {
        emit finished(false);
        return;
    }

    QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    if(!reason.isValid()) {
        qDebug() << "status code=" << statusCode.toInt();
        emit finished(false);
        return;
    }

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
        qDebug() << "reason=" << reason.toString();
        emit finished(false);
    } else {
        QByteArray bytes = reply->readAll();
        QString string = QString::fromUtf8(bytes).simplified();

        QFile f(filePath);
        if (!f.open(QIODevice::WriteOnly)) {
            qDebug() << "open file failed";
            return;
        }
        f.write(bytes);
        f.close();
        emit finished(true);
//        qDebug() << string;
//        analyze(string);
    }
    reply->deleteLater();
}
